﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SyncCommon;
using XPTable.Models;
using HefaSyncTool.SyncManager;
using HefaSyncTool.Properties;
using Newtonsoft.Json;
using HefaSyncTool.Controls;
using SyncCommon.DAL;
using XPTable.Renderers;

namespace HefaSyncTool
{
    public partial class SyncForm : HefaForm
    {
        public delegate void UpdateHanlder(ISyncHouse sender, StatusData data);
        public delegate string ValidateCodeHandler(Image image);
        private SyncCenter Syncs;
        private CellStyle cellStyle;
        private bool isHidden = false;
        private bool isShow = false;
        public SyncForm()
            :base()
        {
            InitializeComponent();
            Syncs= new SyncCenter(this);
        }
        
        protected override void OnClosing(CancelEventArgs e)
        {
            if (!isHidden)
            {
                if (HFMessageBox.ShowCheck("关掉程序会终止正在发送的消息。你确定要这样做吗?", "提示") == System.Windows.Forms.DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
            base.OnClosing(e);
        }
        /// <summary>
        /// 加载表格控件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.SyncTable.BeginUpdate();
            this.cellStyle = new CellStyle();
            this.cellStyle.ForeColor = Color.Blue;
            this.cellStyle.Font = new Font("Courier New", 9.25f, FontStyle.Underline);
            
            TextColumn webSiteColumn = new TextColumn();
            webSiteColumn.Sortable = false;
            webSiteColumn.Editable = false;
            webSiteColumn.Text = "网站";
            webSiteColumn.ToolTipText = "网站名";
            webSiteColumn.Width = 70;

            TextColumn opColumn = new TextColumn();
            opColumn.Sortable = false;
            opColumn.Alignment = ColumnAlignment.Center;
            opColumn.Editable = false;
            opColumn.Text = "状态";
            opColumn.ToolTipText = "状态";
            opColumn.Width = 65;

   
            ProgressBarColumn proColumn = new ProgressBarColumn();
            proColumn.Sortable = false;
            proColumn.Editable = false;
            proColumn.Text = "进度";
            proColumn.ToolTipText = "提交信息的进度";
            proColumn.Width = 180;


            ImageColumn finalColumn = new ImageColumn();
            finalColumn.Alignment = ColumnAlignment.Right;
            finalColumn.Sortable = false;
            //finalColumn.ImageOnRight = false;
            finalColumn.Text = "结果";
            finalColumn.Editable = false;
            finalColumn.Width = 35;

            //TextColumn statusColumn = new TextColumn();
            //statusColumn.Editable = false;
            //statusColumn.Text = "状态";
            //statusColumn.Editable = false;
            //statusColumn.Width = 80;
            //statusColumn.Text = "信息提交状态";

            TextColumn errorColumn = new TextColumn();
            errorColumn.Sortable = false;
            errorColumn.Editable = false;
            errorColumn.Text = "返回信息";
            errorColumn.ToolTipText = "返回信息";
            errorColumn.Width = 175;

            TextColumn urlColumn = new TextColumn();
            urlColumn.Sortable = false;
            urlColumn.Alignment = ColumnAlignment.Center;
            urlColumn.Editable = false;
            urlColumn.Text = "广告位置";
            urlColumn.ToolTipText = "发布成功后的地址";
            
            urlColumn.Width = 70;
            

            HyperLinnkColumn btnColumn = new HyperLinnkColumn();
            btnColumn.Sortable = false;
            btnColumn.Editable = false;
            btnColumn.Width = 180;
            btnColumn.Submit += new HyperLinnkColumn.ClickEventHandler(btnColumn_Submit);
            btnColumn.Refresh += new HyperLinnkColumn.ClickEventHandler(btnColumn_Refresh);
            btnColumn.Delete += new HyperLinnkColumn.ClickEventHandler(btnColumn_Delete);
            btnColumn.Edit += new HyperLinnkColumn.ClickEventHandler(btnColumn_Edit);
            this.SyncTable.CellMouseMove += new XPTable.Events.CellMouseEventHandler(SyncTable_CellMouseMove);
            this.SyncTable.CellMouseLeave += new XPTable.Events.CellMouseEventHandler(SyncTable_CellMouseLeave);
            this.SyncTable.ColumnModel = new ColumnModel(new Column[] {
																	  webSiteColumn,
                                                                      opColumn,
																	  proColumn,
																	  finalColumn,
																	  errorColumn,
                                                                      urlColumn,
                                                                      btnColumn
																	 });

            this.SyncTable.TableModel = new TableModel();
            this.SyncTable.HeaderRenderer = new GradientHeaderRenderer();
            this.SyncTable.HeaderRenderer.Alignment = ColumnAlignment.Center;
            this.SyncTable.TableModel.RowHeight = 20;
            this.SyncTable.EnableToolTips = true;
           
            this.SyncTable.FullRowSelect = true;
            this.SyncTable.CellClick += new XPTable.Events.CellMouseEventHandler(SyncTable_CellClick);
            this.SyncTable.EndUpdate();

            if (!string.IsNullOrEmpty(Program.CommondLine))
            {
              
                ProcessRequest(Program.CommondLine,true);
            }
        }

        void btnColumn_Edit(int row, int col)
        {
            if (!Syncs.OpenEidt(row))
            {
                HFMessageBox.ShowError("登录失败，请检查帐号");
            }
        }

        void SyncTable_CellMouseLeave(object sender, XPTable.Events.CellMouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        void SyncTable_CellMouseMove(object sender, XPTable.Events.CellMouseEventArgs e)
        {
            if (e.Cell != null && e.Cell.Index == 5
                && !string.IsNullOrEmpty(e.Cell.Text))
            {
                this.Cursor = Cursors.Hand;
            }
        }

        void btnColumn_Delete(int row, int col)
        {
            Syncs.SyncInfor(RequestType.Delete, row);
        }

        void btnColumn_Refresh(int row, int col)
        {
            Syncs.SyncInfor(RequestType.Refresh, row);
        }

        void btnColumn_Submit(int row, int col)
        {
            Syncs.SyncInfor(RequestType.Add, row);
        }

        void SyncTable_CellClick(object sender, XPTable.Events.CellMouseEventArgs e)
        {
            if (e.CellPos.Column == 5)
            {
                if (e.Cell.Data != null)
                {
                    UtilMethod.OpenWebBrower(e.Cell.Data.ToString());
                }
            }
        }
        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WINAPI.Message.WM_COPYDATA:
                    WINAPI.COPYDATASTRUCT mystr = (WINAPI.COPYDATASTRUCT)m.GetLParam(typeof(WINAPI.COPYDATASTRUCT));
                    string fangyuanInfo = mystr.lpData;
                    ProcessRequest(fangyuanInfo,false);
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        public void ProcessRequest(string fangyuanInfo,bool hideCurrents)
        {
            fangyuanInfo = fangyuanInfo.Trim();
            string[] retInfo = fangyuanInfo.Split(new Char[] { ',' }, 3);
            //operationType , 0 同步房源信息
            //operationType , 1 账号配置
            //requestType , 0 同步
            //requestType , 1 查看
            if (Syncs.CheckIsSend())
            {
                HFMessageBox.Show("操作不允许！", "工具正在发送消息中！");
                return;
            }
            if (retInfo[0] ==  "1")
            {
                if (isShow)
                {
                    return;
                }
                //MessageBox.Show("Enter");
                if (hideCurrents)
                {
                    isHidden = true;
                    AccountSetting ac = new AccountSetting();
                    isShow = true;
                    ac.ShowDialog();
                    isShow = false;
                    this.Close();
                    Application.Exit();
                }
                else
                {
                    isShow = true;
                    AccountSetting ac = new AccountSetting();
                    ac.ShowDialog();
                    isShow = false;
                }
            }
            else
            {
               
                ClearForm();
                string houseInfo = fangyuanInfo.Substring(retInfo[0].Length + retInfo[1].Length + 2);
                try
                {
                    HouseInfo info = JsonConvert.DeserializeObject<HouseInfo>(houseInfo);

                    this.lbTitle.Text = info.Title;
                    this.lbHefaCode.Text = info.HefaCode;

                    Syncs.HouseInfor = info;
                    Syncs.RestoreStatus();
                    if (retInfo[1] == "0")
                    {
                        Syncs.SyncNewHouseInfo(RequestType.Add);
                    }
                }
                catch (Exception exp)
                {
                    LogCenter.Log(exp);
                }
            }
        }

        public void ClearForm()
        {
            SyncTable.TableModel.Rows.Clear();

        }

        public RequestType GetRequestType(string input)
        {
            string ret = input.Trim();
            return (RequestType)int.Parse(ret);
        }

        public int AddNewRow(string op, string website, int progress, bool final, string error, string url, bool isRefresh,RequestType requestType)
        {
            Row newRow = new Row(new Cell[] { 
			    new Cell(website),
                 new Cell(op),
				 new Cell(progress),
                 new Cell("",final?Resources.Correct:Resources.Wrong),
                  new Cell(error),
                  new Cell(""),
                 new Cell(""){ Data=isRefresh}
            });
            if (!string.IsNullOrEmpty(url))
            {
                newRow.Cells[5].Text = "查看";
                newRow.Cells[5].Data = url;
            }
            if (requestType == RequestType.Add && final)
            {
                newRow.Cells[6].Text = "1";
            }
            
            newRow.Cells[5].CellStyle = cellStyle;
            newRow.Cells[6].CellStyle = cellStyle;
            SyncTable.TableModel.Rows.Add(newRow);
            return newRow.Index;
        }

        public int AddNewRow(string op, string website,bool isRefresh)
        {
            Row newRow = new Row(new Cell[] { 
			    new Cell(website),
                 new Cell(op),
				 new Cell(0),
                 new Cell(""),
                  new Cell(""),
                  new Cell(""),
                  new Cell(""){ Data=isRefresh}
            });

         
            newRow.Cells[5].CellStyle = cellStyle;
            newRow.Cells[6].CellStyle = cellStyle;
            SyncTable.TableModel.Rows.Add(newRow);
            return newRow.Index;
        }

        public void UpdateRow(ISyncHouse sender,StatusData data)
        {
            this.Invoke(new UpdateHanlder(UpdateRowInternal), sender, data);
        }
        public string ValidationCodeValue(Image image)
        {
            return (string)this.Invoke(new ValidateCodeHandler(GetValidataionCode), image);
        }

        private string GetValidataionCode(Image image)
        {
            ValidationForm v = new ValidationForm();
            v.CodeImage = image;
            if (v.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                return v.Code;
            }
            return "";
        }

        public void ClearRecord(int RowId, RequestType type)
        {
            SyncTable.TableModel.Rows[RowId].Cells[1].Text = "";
            SyncTable.TableModel.Rows[RowId].Cells[4].Text = "";
            if (type != RequestType.Refresh)//刷新不清空超链接
            {
                SyncTable.TableModel.Rows[RowId].Cells[5].Text = "";
                SyncTable.TableModel.Rows[RowId].Cells[5].Data = null;
            }
            SyncTable.TableModel.Rows[RowId].Cells[3].Image = null;
        }
        /// <summary>
        /// 数据提交后的界面更新
        /// </summary>
        /// <param name="progress"></param>
        /// <param name="error"></param>
        /// <param name="rowID"></param>
        private void UpdateRowInternal(ISyncHouse sender, StatusData data)
        {
            
            if (data.Progress == StandardProgress.InitalData)
            {
                ClearRecord(data.RowID,data.requestType);
                SyncTable.TableModel.Rows[data.RowID].Cells[2].Data = 30;
                //SyncTable.TableModel.Rows[data.RowID].Cells[1].Text = UtilMethod.GetRequestDesc(data.requestType);
            }
            if (data.Progress == StandardProgress.PosData)
            {
                SyncTable.TableModel.Rows[data.RowID].Cells[2].Data = 60;
            }
            if (data.Progress == StandardProgress.Failed)
            {
               
                SyncTable.TableModel.Rows[data.RowID].Cells[2].Data = 100;
                SyncTable.TableModel.Rows[data.RowID].Cells[4].Text = data.Status;
                SyncTable.TableModel.Rows[data.RowID].Cells[3].Image = Resources.Wrong;
                SyncTable.TableModel.Rows[data.RowID].Cells[1].Text = UtilMethod.GetOpStatus(data.requestType,false);
            }
            if (data.Progress == StandardProgress.Sucess)
            {
                SyncTable.TableModel.Rows[data.RowID].Cells[6].Text = "";
                SyncTable.TableModel.Rows[data.RowID].Cells[2].Data = 100;
                SyncTable.TableModel.Rows[data.RowID].Cells[4].Text = data.Status;
                SyncTable.TableModel.Rows[data.RowID].Cells[1].Text = UtilMethod.GetOpStatus(data.requestType, true);
                
                if (!string.IsNullOrEmpty(data.Url))
                {
                    SyncTable.TableModel.Rows[data.RowID].Cells[5].Text = "查看";
                    SyncTable.TableModel.Rows[data.RowID].Cells[5].Data = data.Url;
                }
                SyncTable.TableModel.Rows[data.RowID].Cells[3].Image = Resources.Correct;
                //添加成功。设置重发失效
                if (data.requestType == RequestType.Add)
                {
                    SyncTable.TableModel.Rows[data.RowID].Cells[6].Text = "1";
                }
                if (data.requestType == RequestType.Delete)
                {
                    SyncTable.TableModel.Rows[data.RowID].Cells[6].Text = "";
                }
            }
        }

        private void btnRefreshAll_Click(object sender, EventArgs e)
        {
            Syncs.SyncNewHouseInfo(RequestType.Refresh);
        }

        private void btnDeleteAll_Click(object sender, EventArgs e)
        {
            Syncs.SyncNewHouseInfo(RequestType.Delete);
        }

        private void btnSetAccount_Click(object sender, EventArgs e)
        {
            AccountSetting ac = new AccountSetting();
            ac.ShowDialog();
        }        
    }
}
